<template>
  <h3>{{ course.name }}</h3>
  <hr>
  <p>
    <router-link to="/business/course" class="btn btn-white btn-default">
      <i class="ace-icon fa fa-arrow-left"></i>
      返回课程
    </router-link>
    &nbsp;
    <button @click="add" class="btn btn-white btn-default">
      <i class="ace-icon fa fa-edit"></i>
      新增
    </button>
    &nbsp;
    <button @click="refresh" class="btn btn-white btn-default">
      <i class="ace-icon fa fa-undo"></i>
      刷新
    </button>
  </p>
  <table id="simple-table" class="table  table-bordered table-hover">
    <thead>
    <tr>
      <th>ID</th>
      <th>名称</th>
      <th>操作</th>
    </tr>
    </thead>

    <tbody>
    <tr v-for="c in chapterArray" :key="c.id">
      <td>{{ c.id }}</td>
      <td>{{ c.name }}</td>
      <td>
        <div class="hidden-sm hidden-xs btn-group">
          <button @click="toSection(c)" class="btn btn-xs btn-info">
            小节
          </button>

          <button @click="edit(c)" class="btn btn-xs btn-info">
            编辑
          </button>

          <button @click="del(c.id)" class="btn btn-xs btn-danger">
            删除
          </button>
        </div>

        <div class="hidden-md hidden-lg">
          <div class="inline pos-rel">
            <button class="btn btn-minier btn-primary dropdown-toggle" data-toggle="dropdown" data-position="auto">
              <i class="ace-icon fa fa-cog icon-only bigger-110"></i>
            </button>

            <ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
              <li>
                <a href="#" class="tooltip-info" data-rel="tooltip" title="View">
																			<span class="blue">
																				<i class="ace-icon fa fa-search-plus bigger-120"></i>
																			</span>
                </a>
              </li>

              <li>
                <a href="#" class="tooltip-success" data-rel="tooltip" title="Edit">
																			<span class="green">
																				<i class="ace-icon fa fa-pencil-square-o bigger-120"></i>
																			</span>
                </a>
              </li>

              <li>
                <a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
																			<span class="red">
																				<i class="ace-icon fa fa-trash-o bigger-120"></i>
																			</span>
                </a>
              </li>
            </ul>
          </div>
        </div>
      </td>
    </tr>
    </tbody>
  </table>
  <!-- 分页插件 -->
  <pagination ref="paginationRef" :list="getChapterList" />

  <!-- Modal -->
  <div class="modal fade" id="form-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">表单</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal">
            <div class="form-group">
              <label class="col-sm-2 control-label">名称</label>
              <div class="col-sm-10">
                <input v-model="chapter.name" type="text" class="form-control" placeholder="名称">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-2 control-label">课程</label>
              <div class="col-sm-10">
                <p class="form-control-static">{{course.name}}</p>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button @click="saveChapter" type="button" class="btn btn-primary">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {onMounted, ref} from "vue";
import pagination from "@/components/pagination";
import {useRouter} from "vue-router";

export default {
  name: "Chapter",
  components: {
    pagination,
  },
  setup() {
    const chapterArray = ref([]);
    const chapter = ref({}); // 保存大章表单
    const paginationRef = ref(null);

    const course = ref({});
    const router = useRouter();

    // 刷新
    const refresh = () => {
      getChapterList(1);
    }

    // 获取大章列表
    const getChapterList = (page) => {
      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/chapter/list",
          {
            page: page,
            size: paginationRef.value.size,
            courseId: course.value.id
          }
      ).then((response) => {
        Loading.hide();
        const resp = response.data;
        chapterArray.value = resp.content.list;
        paginationRef.value.render(page, resp.content.total);
      })
    }

    // 保存大章
    const saveChapter = () => {
      chapter.value.courseId = course.value.id;
      // 保存参数校验
      if(!Validator.require(chapter.value.name, '名称')
          || !Validator.length(chapter.value.courseId, '课程ID', 1, 8)) {
          return;
      }

      Loading.show();
      axios.post(process.env.VUE_APP_SERVER + "/business/admin/chapter/save", chapter.value).then((response) => {
        const resp = response.data;
        if (resp.success) {
          Loading.hide();
          $('#form-modal').modal('hide');
          Toast.success("保存成功");
          getChapterList(1);
        } else {
          Loading.hide();
          $('#form-modal').modal('hide');
          Toast.warning(resp.message);
        }
      })
    }

    // 删除大章
    const del = (id) => {
      Confirm.show("删除后不可恢复，确认删除？", function () {
        Loading.show();
        axios.delete(process.env.VUE_APP_SERVER + "/business/admin/chapter/delete/" + id).then((response) => {
          const resp = response.data;
          if (resp.success) {
            //$('#form-modal').modal('hide');
            getChapterList(1);
          }
        })
        Toast.success("删除成功");
      })

      // Swal.fire({
      //   title: '确认删除?',
      //   text: "You won't be able to revert this!",
      //   icon: 'warning',
      //   showCancelButton: true,
      //   confirmButtonColor: '#3085d6',
      //   cancelButtonColor: '#d33',
      //   confirmButtonText: '确认'
      // }).then((result) => {
      //   if (result.value) {
      //     Loading.show();
      //     axios.delete("http://localhost:9000/business/admin/chapter/delete/" + id).then((response) => {
      //       const resp = response.data;
      //       if (resp.success) {
      //         //$('#form-modal').modal('hide');
      //         getChapterList(1);
      //       }
      //     })
      //     Toast.success("删除成功");
      //   }
      // })
    }

    // 打开模态框
    const add = () => {
      chapter.value = {};
      $('#form-modal').modal('show');
    }

    // 修改大章
    const edit = (c) => {
      // 方法一
      //chapter.value = JSON.parse(JSON.stringify(c));
      // 方法二
      chapter.value = $.extend({}, c);
      console.log(chapter.value)
      $('#form-modal').modal('show');
    }

    /**
     * 点击 【小节】
     */
    const toSection = (params) => {
      SessionStorage.set(SESSION_KEY_CHAPTER, params);
      router.push("/business/section");
    }

    // 初始加载第一页
    onMounted(() => {
      // 把sessionStorage中的课程取出来（跳转 需求）
      const session_course = SessionStorage.get(SESSION_KEY_COURSE) || {};
      if (Tool.isEmpty(session_course)) {
        router.push("/welcome");
      }
      course.value = session_course;
      getChapterList(1);
    })

    return {
      chapterArray,
      refresh,
      paginationRef,
      getChapterList,
      add,
      saveChapter,
      chapter,
      edit,
      del,
      course,
      toSection
    }
  }
}
</script>

<style scoped>

</style>